package my.web;

import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.startup.Tomcat;

/**
 * 应用启动类
 * @author 夏冬琦
 *
 */
public class My {
	
	
	
	private static int port;
	private static String baseDir;
	private static String classPath;
	private static Tomcat tomcat;
	private static Context ctx;
	
	
	/**
	 * 启动应用，在80端口监听
	 */
	public static void run() {
		run(80);
	}

	/**
	 * 启动应用，在指定端口监听
	 * @param port 端口号
	 */
	public static void run(int port) {
		
		
		My.port = port;
		
		classPath = My.class.getResource("/").getPath();
		
		//baseDir = new File(classPath).getParentFile().getAbsolutePath();

		tomcat = new Tomcat();
		tomcat.setBaseDir(classPath);
		tomcat.setPort(My.port);
		

		ctx = tomcat.addWebapp("", classPath+"/static");
		ctx.setReloadable(true);
		ctx.setRequestCharacterEncoding("UTF-8");
		
		
		Connector connector = tomcat.getConnector();
        connector.setAttribute("maxThreads", 500);

		try {
			tomcat.init();
			tomcat.start();
//			
//			new Thread() {
//				
//				@Override
//				public void run() {
//					Reader in = new InputStreamReader(System.in);
//					while(true) {
//						try {
//							System.out.println("按回车键，重启服务器...");
//							if(in.read()=='\r') {
//								tomcat.stop();								
//								tomcat.start();
//								System.out.println("已成功重启服务器！");
//							}
//						} catch (IOException e) {
//							// TODO Auto-generated catch block
//							e.printStackTrace();
//						} catch (LifecycleException e) {
//							// TODO Auto-generated catch block
//							e.printStackTrace();
//						}
//					}
//				}
//				
//			}.start();
//			
			
			tomcat.getServer().await();
		} catch (LifecycleException e) {
			e.printStackTrace();
		}
		
		
	}

}
